//
// Created by yangchao on 2022/5/25.
// 103. 二叉树的锯齿形层序遍历: https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/
//

#include <vector>
#include <queue>
#include "../DataStructure/TreeNode.h"

using namespace std;

class ZigzagLevelOrder {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        if (root == nullptr) return {};
        bool b = false;
        vector<vector<int>> res;
        queue<TreeNode*> q;
        q.emplace(root);
        while (!q.empty()) {
            int len = q.size();
            vector<int> v(len);
            for (int i = 0; i < len; ++i) {
                TreeNode *node = q.front();
                q.pop();
                //实现正插和反插
                v[b ? len-1-i : i] = node->val;
                if (node->left != nullptr) q.emplace(node->left);
                if (node->right != nullptr) q.emplace(node->right);
            }
            res.emplace_back(v);
            b = !b;
        }
        return res;
    }
};

